<script setup>
/*----------------------* 后台管理员页面主框架 *----------------------*/

import {
  ArrowDown,
  ChatDotRound,
  Document,
  House,
  Lock,
  Monitor,
  Setting,
  ShoppingCart,
  Unlock,
  User
} from "@element-plus/icons-vue";
import {onMounted, onUnmounted, ref, watch} from 'vue';
import {useRoute, useRouter} from 'vue-router';
import {ElMessage} from "element-plus";

const route = useRoute();
const router = useRouter();

const activeMenu = ref('')

// 当前用户实体（默认显示管理员，可根据登录态修改）
const userInfo = ref({username: '管理员'})

// 标签页相关状态 - 初始化路径使用完整路由
const tabs = ref([])
const activeTab = ref('')

// 路由与标签页映射 - 新增“违规封禁”子路由
const routeMap = {
  '/System/Portal': {id: 'Portal', name: '首页', closable: false},
  '/System/User': {id: 'User', name: '用户管理', closable: true},
  '/System/ArticleDto': {id: 'ArticleDto', name: '文章管理', closable: true},
  '/System/Activity': {id: 'Activity', name: '活动管理', closable: true},
  '/System/feedback': {id: 'feedback', name: '问题反馈', closable: true},
  '/System/UserBan': {id: 'UserBan', name: '用户封禁', closable: true},
  '/System/ArticleDtoBan': {id: 'ArticleDtoBan', name: '文章封禁', closable: true},
  '/System/GoodsManagement': {id: 'GoodsManagement', name: '商品管理', closable: true}
};

// 初始化标签页 - 支持路由自适应
const initTabs = () => {
  const currentPath = route.path;
  const targetTab = routeMap[currentPath] || routeMap['/System/Portal'];

  tabs.value = [{
    id: targetTab.id,
    name: targetTab.name,
    closable: targetTab.closable,
    path: currentPath
  }];
  activeTab.value = targetTab.id;
  activeMenu.value = targetTab.id;
};

// 窗口大小监听 - 修复高度自适应问题
const handleResize = () => {
  const container = document.getElementById('container');
  if (container) {
    container.style.height = `${window.innerHeight}px`;
  }
};

// 页面加载时初始化+监听窗口变化
onMounted(() => {
  const router = useRouter()
  const isLogged = sessionStorage.getItem('isLogged') === 'true'
  const role = sessionStorage.getItem('role')
  if (!isLogged) {
    ElMessage.warning('请先登录')
    router.push('/login')
    return;
  }
  if (role !== '3') {
    ElMessage.error('无权限访问该页面')
    router.push('/login')
    return;
  }
  initTabs();
  handleResize();
  window.addEventListener('resize', handleResize);
});

// 页面卸载时移除监听
onUnmounted(() => {
  window.removeEventListener('resize', handleResize);
});

// 添加或激活标签页 - 去重逻辑优化
const addOrActivateTab = (tabInfo, path) => {
  const existingTabIndex = tabs.value.findIndex(tab => tab.id === tabInfo.id);
  if (existingTabIndex > -1) {
    activeTab.value = tabInfo.id;
    tabs.value[existingTabIndex].path = path;
  } else {
    tabs.value.push({
      id: tabInfo.id,
      name: tabInfo.name,
      closable: tabInfo.closable,
      path: path
    });
    activeTab.value = tabInfo.id;
  }
};

// 监听路由变化，同步标签和菜单状态
watch(() => route.path, (newPath) => {
  const tabInfo = routeMap[newPath];
  if (tabInfo) {
    addOrActivateTab(tabInfo, newPath);
    activeMenu.value = tabInfo.id;
  } else {
    router.push('/System/Portal');
  }
}, {immediate: true});

// 菜单切换 - 关联路由路径
const handleMenuSelect = (index) => {
  const pathMap = {
    'Portal': '/System/Portal',
    'User': '/System/User',
    'ArticleDto': '/System/ArticleDto',
    'Activity': '/System/Activity',
    'feedback': '/System/feedback',
    'UserBan': '/System/UserBan',
    'ArticleDtoBan': '/System/ArticleDtoBan',
    'GoodsManagement': '/System/GoodsManagement'
  };
  const path = pathMap[index] || '/System/Portal';
  router.push(path);
}

// 切换标签页：跳转对应路由
const switchTab = (tabId) => {
  const tab = tabs.value.find(t => t.id === tabId);
  if (tab) {
    router.push(tab.path);
  }
};

// 关闭标签页：避免关闭唯一标签
const closeTab = (tabId) => {
  if (tabs.value.length <= 1) return;

  const tabIndex = tabs.value.findIndex(tab => tab.id === tabId);
  tabs.value.splice(tabIndex, 1);

  if (activeTab.value === tabId) {
    const newActiveIndex = Math.max(0, tabIndex - 1);
    const newActiveTab = tabs.value[newActiveIndex];
    router.push(newActiveTab.path);
  }
};

// 关闭其他标签页
const closeOtherTabs = () => {
  tabs.value = tabs.value.filter(tab => !tab.closable || tab.id === activeTab.value);
};

// 关闭所有标签页
const closeAllTabs = () => {
  tabs.value = tabs.value.filter(tab => !tab.closable);
  router.push('/System/Portal');
};

// 标签页下拉菜单命令处理
const handleTabCommand = (command) => {
  switch (command) {
    case 'closeOther':
      closeOtherTabs();
      break;
    case 'closeAll':
      closeAllTabs();
      break;
  }
};

// 用户下拉菜单命令处理
const handleCommand = (command) => {
  switch (command) {
    case 'profile':
      router.push('/userInfo');
      break;
    case 'logout':
      sessionStorage.removeItem('token');
      sessionStorage.removeItem('adminName');
      router.push('/login');
      ElMessage.success('退出登录成功');

      break;
  }
}
</script>

<template>
  <!-- 主框架容器（100%窗口高度） -->
  <el-container id="container" class="full-height">
    <!-- 侧边栏（固定宽度，100%高度） -->
    <el-aside class="aside-container" width="220px">
      <el-menu
          :default-active="activeMenu"
          background-color="#fff"
          class="menu-container"
          @select="handleMenuSelect"
          text-color="#333"
      >
        <!-- Logo区域 -->
        <div class="logo-area" @click="router.push('/')">
          <h1 class="system-title ">DevPlatform</h1>
        </div>

        <!-- 中间菜单区域 -->
        <div class="middle-menu">
          <el-menu-item index="Portal">
            <el-icon class="menu-icon">
              <House/>
            </el-icon>
            <span>首页</span>
          </el-menu-item>

          <el-sub-menu index="System">
            <template #title>
              <el-icon class="menu-icon">
                <Setting/>
              </el-icon>
              <span>系统管理</span>
            </template>
            <el-menu-item index="User">
              <el-icon class="menu-icon">
                <User/>
              </el-icon>
              <span>用户管理</span>
            </el-menu-item>
            <el-menu-item index="ArticleDto">
              <el-icon class="menu-icon">
                <Document/>
              </el-icon>
              <span>文章管理</span>
            </el-menu-item>
            <!--            <el-menu-item index="Activity">-->
            <!--              <el-icon class="menu-icon">-->
            <!--                <Promotion/>-->
            <!--              </el-icon>-->
            <!--              <span>活动管理</span>-->
            <!--            </el-menu-item>-->
            <el-menu-item index="GoodsManagement">
              <el-icon class="menu-icon">
                <ShoppingCart/>
              </el-icon>
              <span>商品管理</span>
            </el-menu-item>
          </el-sub-menu>

          <el-sub-menu index="Ban">
            <template #title>
              <el-icon class="menu-icon">
                <Lock/>
              </el-icon>
              <span>违规封禁</span>
            </template>
            <el-menu-item index="UserBan">
              <el-icon class="menu-icon">
                <Unlock/>
              </el-icon>
              <span>用户封禁</span>
            </el-menu-item>
            <el-menu-item index="ArticleDtoBan">
              <el-icon class="menu-icon">
                <Unlock/>
              </el-icon>
              <span>文章封禁</span>
            </el-menu-item>
          </el-sub-menu>
        </div>

        <!-- 底部问题反馈菜单 -->
        <div class="bottom-menu">
          <el-menu-item index="feedback">
            <el-icon class="menu-icon">
              <ChatDotRound/>
            </el-icon>
            <span>问题反馈</span>
          </el-menu-item>
        </div>
      </el-menu>
    </el-aside>

    <!-- 右侧主内容区（自适应宽度） -->
    <el-container class="main-container">
      <!-- 顶栏（固定高度60px） -->
      <el-header class="header-container">
        <div class="header-left">
          <el-icon size="22">
            <Monitor/>
          </el-icon>
          <span class="header-title">开发者后台管理系统</span>
        </div>
        <div class="header-right">
          <el-dropdown class="user-dropdown" @command="handleCommand">
            <span class="el-dropdown-link">
              <el-icon><User/></el-icon>
              <span>欢迎您, {{ userInfo.username }}</span>
              <el-icon><ArrowDown/></el-icon>
            </span>
            <template #dropdown>
              <el-dropdown-menu>
                <el-dropdown-item command="profile">个人中心</el-dropdown-item>
                <el-dropdown-item command="logout" divided>退出登录</el-dropdown-item>
              </el-dropdown-menu>
            </template>
          </el-dropdown>
        </div>
      </el-header>

      <!-- 标签页导航栏（固定高度48px） -->
      <div class="tabs-container">
        <div class="tabs-wrapper">
          <div
              v-for="tab in tabs"
              :key="tab.id"
              :class="['tab-item', { 'tab-active': tab.id === activeTab }]"
              @click="switchTab(tab.id)"
          >
            <span class="tab-name">{{ tab.name }}</span>
            <span
                v-if="tab.closable"
                class="tab-close"
                @click.stop="closeTab(tab.id)"
            >×</span>
          </div>
        </div>
        <el-dropdown class="tabs-dropdown" @command="handleTabCommand">
          <el-button size="small" text>
            <el-icon>
              <ArrowDown/>
            </el-icon>
          </el-button>
          <template #dropdown>
            <el-dropdown-menu>
              <el-dropdown-item command="closeOther">关闭其他</el-dropdown-item>
              <el-dropdown-item command="closeAll">关闭所有</el-dropdown-item>
            </el-dropdown-menu>
          </template>
        </el-dropdown>
      </div>

      <!-- 主内容区（剩余高度自适应） -->
      <el-main class="content-container">
        <router-view v-slot="{ Component }">
          <keep-alive>
            <component :is="Component" :key="route.fullPath"/>
          </keep-alive>
        </router-view>
      </el-main>
    </el-container>
  </el-container>
</template>

<style scoped>
/* 基础样式重置 */
* {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
}

/* 100%高度容器 */
.full-height {
  height: 100vh;
  overflow: hidden;
}

/* 侧边栏容器（100%高度） */
.aside-container {
  height: 100%;
  border-right: 1px solid #e8e8e8;
  box-shadow: 2px 0 8px rgba(0, 0, 0, 0.05);
  overflow: hidden;
}

/* 菜单容器（100%高度，flex布局） */
.menu-container {
  border: none !important;
  height: 100%;
  display: flex;
  flex-direction: column;
  padding: 15px 0;
}

/* Logo区域 */
.logo-area {
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 20px 15px;
  border-bottom: 1px solid #e8e8e8;
  text-align: center;
}

.logo {
  margin-bottom: 8px;
}

.system-title {
  font-size: 23px;
  font-weight: 600;
  color: #2563eb;
}

/* 中间菜单区域（自适应填充） */
.middle-menu {
  flex: 1;
  padding-top: 10px;
  overflow-y: auto;
  scrollbar-width: thin;
}

.middle-menu::-webkit-scrollbar {
  width: 4px;
}

.middle-menu::-webkit-scrollbar-thumb {
  background-color: #e8e8e8;
  border-radius: 2px;
}

/* 菜单项样式 */
.menu-container :deep(.el-menu-item),
.menu-container :deep(.el-sub-menu__title) {
  margin: 6px 10px;
  border-radius: 6px;
  padding: 12px 20px !important;
  height: 44px !important;
  font-size: 14px;
  transition: background-color 0.2s;
}

/* 子菜单缩进调整 */
.menu-container :deep(.el-sub-menu .el-menu-item) {
  padding-left: 50px !important;
}

/* 菜单图标 */
.menu-icon {
  margin-right: 10px;
  font-size: 16px;
}

/* 菜单项hover效果 */
.menu-container :deep(.el-menu-item:hover),
.menu-container :deep(.el-sub-menu__title:hover) {
  background-color: #f5f7fa !important;
}

/* 菜单项激活状态 */
.menu-container :deep(.el-menu-item.is-active) {
  background-color: #e6f7ff !important;
  color: #1890ff !important;
}

/* 底部菜单 */
.bottom-menu {
  margin-top: auto;
  padding: 10px 0;
  border-top: 1px solid #e8e8e8;
}

/* 顶栏容器（固定高度） */
.header-container {
  height: 60px !important;
  border-bottom: 1px solid #e8e8e8;
  padding: 0 24px;
  display: flex;
  align-items: center;
  justify-content: space-between;
}

.header-left {
  display: flex;
  align-items: center;
  gap: 12px;
}

.header-title {
  font-size: 18px;
  font-weight: 600;
  color: #333;
}

/* 用户下拉菜单 */
.user-dropdown {
  cursor: pointer;
}

.el-dropdown-link {
  display: flex;
  align-items: center;
  gap: 8px;
  padding: 6px 12px;
  border-radius: 4px;
  transition: background-color 0.2s;
}

.el-dropdown-link:hover {
  background-color: #f5f7fa;
}

/* 标签页容器（固定高度） */
.tabs-container {
  height: 48px !important;
  border-bottom: 1px solid #e8e8e8;
  display: flex;
  align-items: center;
  padding: 0 16px;
}

.tabs-wrapper {
  flex: 1;
  display: flex;
  gap: 4px;
  overflow-x: auto;
  scrollbar-width: none;
  padding: 4px 0;
}

.tabs-wrapper::-webkit-scrollbar {
  display: none;
}

/* 标签项样式 */
.tab-item {
  padding: 0 16px;
  height: 36px;
  display: flex;
  align-items: center;
  gap: 8px;
  background-color: #f5f7fa;
  border: 1px solid transparent;
  border-radius: 4px 4px 0 0;
  cursor: pointer;
  white-space: nowrap;
  transition: all 0.2s;
}

.tab-item:hover {
  background-color: #e6f0ff;
}

.tab-active {
  background-color: #fff;
  border-color: #e8e8e8;
  border-bottom-color: transparent;
  color: #1890ff;
  font-weight: 500;
}

.tab-close {
  width: 16px;
  height: 16px;
  display: flex;
  align-items: center;
  justify-content: center;
  border-radius: 50%;
  font-size: 12px;
  transition: background-color 0.2s;
}

.tab-close:hover {
  background-color: rgba(0, 0, 0, 0.1);
}

/* 主内容区（自适应剩余高度） */
.content-container {
  flex: 1;
  padding: 20px;
  background-color: #f5f7fa;
  overflow-y: auto;
  scrollbar-width: thin;
}

.content-container::-webkit-scrollbar {
  width: 6px;
}

.content-container::-webkit-scrollbar-thumb {
  background-color: #d9d9d9;
  border-radius: 3px;
}

/* 下拉菜单样式优化 */
:deep(.el-dropdown-menu) {
  border-radius: 4px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
}

:deep(.el-dropdown-item) {
  padding: 8px 16px;
  transition: background-color 0.2s;
}

:deep(.el-dropdown-item:hover) {
  background-color: #f5f7fa;
}
</style>